<template>
	<el-dialog title="提示" :visible.sync="visible" width="640px" :close-on-click-modal="false" class="subject_dialog_wrapper">
		<el-form :model="subjectForm" ref="subjectForm" class="subject_content" size="small">
			<el-form-item prop="content" label="题目名称" class="subject_title" :rules="{ required: true, message: '请输入题目标题', trigger: 'blur' }">
				<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="subjectForm.content"></el-input>
			</el-form-item>
			<template v-if="subjectType !== '3' && subjectType !== '5'">
				<el-form-item label="答案选项" class="options_title"><el-button type="text" @click="addSubjectOption">添加选项</el-button></el-form-item>
				<el-form-item
					v-for="(option, index) in subjectForm.options"
					class="subject_option"
					:label="letterArr.charAt(index)"
					:prop="'options.' + index + '.value'"
					:rules="optionRules"
				>
					<el-input type="textarea" autosize v-model="option.value"></el-input>
					<el-button type="text" @click.prevent="delSubjectOption(index)">删除</el-button>
				</el-form-item>
			</template>
		</el-form>
		<template slot="footer">
			<el-button size="small" @click="visible = false">取 消</el-button>
			<el-button size="small" type="primary" @click="handleSubmitForm" :loading="loading">确 定</el-button>
		</template>
	</el-dialog>
</template>

<script>
import { tbQuestionnaireContentAdd, tbQuestionnaireContentUpdate } from '@/api/admin/survey/tbQuestionnaireContent';
export default {
	props: {
		value: {
			type: Boolean,
			defalut: false
		},
		data: Object,
		subjectType: String
	},
	data() {
		const customRules = (rule, value, callback) => {
			let dataArr = this.deepClone(this.subjectForm.options);
			dataArr.splice(Number(rule.field.split('.')[1]), 1);
			if (dataArr.some(item => item.value === value)) {
				callback(new Error('存在相同选项'));
			} else {
				callback();
			}
		};
		return {
			visible: this.value,
			loading: false,
			addOrEdit: false,
			letterArr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
			optionRules: [{ required: true, message: '选项不能为空', trigger: 'blur' }, { validator: customRules, trigger: 'blur' }],
			subjectForm: {
				content: '',
				options: []
			}
		};
	},
	watch: {
		value(val) {
			this.visible = val;
		},
		visible(val) {
			this.$emit('input', val);
			if (!val) {
				this.$refs['subjectForm'].resetFields();
				this.subjectForm.content = '';
				this.subjectForm.options = [];
			} else {
				let objectArr = Object.keys(this.data);
				if (objectArr.length === 0) {
					this.addOrEdit = true;
				} else {
					let answerArr = objectArr.filter(item => item.indexOf('questionOption') !== -1);
					this.addOrEdit = false;
					this.subjectForm.content = this.data.content;
					this.subjectForm.options = answerArr.map(item => {
						return {
							key: 'questionOption',
							value: this.data[item]
						};
					});
				}
			}
		}
	},
	methods: {
		//提交表单
		handleSubmitForm() {
			this.$refs['subjectForm'].validate(async valid => {
				if (!valid) return false;
				this.loading = true;
				if (!this.addOrEdit) {
					await this.updateSubjectRequest();
				} else {
					await this.addSubjectRequest();
				}
				this.loading = false;
				this.visible = false;
			});
		},

		//格式化题目参数
		formatSubjectParams() {
			let params = { content: this.subjectForm.content, courseId: '999', type: this.subjectType };
			this.subjectForm.options.forEach((item, index) => {
				params[item.key + (index + 1)] = item.value;
			});
			if (!this.addOrEdit) params['id'] = this.data.id;
			return params;
		},

		//添加题目请求
		async addSubjectRequest() {
			let params = this.formatSubjectParams();
			let result = await tbQuestionnaireContentAdd(params).then(res => res.data);
			if (result.code === '0') {
				this.$message.success('题目添加成功');
				this.$emit('finish');
			}
		},

		//修改题目请求
		async updateSubjectRequest() {
			let params = this.formatSubjectParams();
			let result = await tbQuestionnaireContentUpdate(params).then(res => res.data);
			if (result.code === '0') {
				this.$message.success('题目修改成功');
				this.$emit('finish');
			}
		},

		//添加选项
		addSubjectOption() {
			this.subjectForm.options.push({
				key: 'questionOption',
				value: ''
			});
		},

		//删除选项
		delSubjectOption(index) {
			this.subjectForm.options.splice(index, 1);
		}
	}
};
</script>

<style lang="scss" scoped>
.subject_dialog_wrapper ::v-deep {
	.el-dialog__header {
		padding: 15px;
		line-height: 1;
		border-bottom: solid 1px #eee;
	}
	.el-dialog__headerbtn {
		top: 15px;
		right: 15px;
	}
	.el-dialog__body {
		padding: 10px 20px 30px;
		max-height: 500px;
		overflow: auto;
	}
	.el-dialog__footer {
		padding: 15px;
		border-top: solid 1px #eee;
	}
}
.subject_content ::v-deep {
	.el-form-item:last-child {
		margin-bottom: 0;
	}
	.el-textarea__inner {
		resize: none;
		font-family: 'MicrosoftYahei';
	}
}
.subject_title ::v-deep {
	.el-form-item__label {
		float: none;
		font-weight: bold;
	}
}
.options_title ::v-deep {
	overflow: hidden;
	.el-form-item__label {
		font-weight: bold;
		line-height: 1;
	}
	.el-form-item__content {
		float: right;
		line-height: 1;
	}
	.el-button--text {
		padding: 0;
	}
}
.subject_option ::v-deep {
	.el-form-item__content {
		display: flex;
		align-items: flex-start;
	}
	.el-button--small {
		margin-left: 10px;
	}
}
</style>
